package com.paipai.controller;

import java.io.File;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.paipai.entity.Address;
import com.paipai.entity.User;
import com.paipai.service.AddressService;
import com.paipai.service.AuthCodeServlet;
import com.paipai.service.UserService;
import com.paipai.utils.AuthCodeUtils;
import com.paipai.utils.BaseController;

@Controller
public class UserController extends BaseController {

	static final String KEY_PREFIX = "user:code:phone:";

	@Autowired
	private AuthCodeServlet acs;

	@Autowired
	private UserService us;

	@Autowired
	private AmqpTemplate amtle;

	@Autowired
	private StringRedisTemplate srtle;

	/**
	 * 发送验证码
	 * 
	 * @param date
	 */
	@ResponseBody
	@RequestMapping("/sendAuthCode")
	// 接受post参数
	public String sendAuthCode(String phone) {
		try {
			
			BoundValueOperations<String, String> valueOps = srtle.boundValueOps("phoneRepetition:" + phone);
			
			// 放重复提交
			if (valueOps.get() != null) {
				return "repetition";
			}
			
			
			// 随机验证码
			String random = AuthCodeUtils.getRandom();
			// map保存 手机号码 随机码
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("random", random);
			map.put("phone", phone);
			// 发送消息队列
			amtle.convertAndSend("paipai.sms.exchange", "sms.verify.code", map);
			// redis 保存随机码
			ValueOperations<String, String> forValue = srtle.opsForValue();
			// 有效期五分钟
			forValue.set(KEY_PREFIX + phone, random, 5, TimeUnit.MINUTES);
			// 再redis 放入防重复数据  一分钟有效
			valueOps.set("A", 1, TimeUnit.MINUTES);
			return "yes";
		} catch (Exception e) {
			// 发生异常 返回no
			e.printStackTrace();
			return "no";
		}

	}

	/**
	 * 检查验证码时候正确
	 * 
	 * @param date
	 */
	@ResponseBody
	@RequestMapping("/authCodeVerify")
	// 接受post参数
	public String authCodeVerify(String authCode, String phone) {

		Boolean flag = us.authCodeVerify(authCode, phone);

		// 验证码 正确/错误
		return flag ? "ok" : "no";
	}

	/**
	 * 检查注册用户名/手机是否重复
	 * 
	 * @param date
	 */
	@ResponseBody
	@RequestMapping("/unameVerify")
	public String unameVerify(String value, Integer type) {
		Boolean flag = us.unameVerify(value, type);

		// 是否已经被注册
		return flag ? "ok" : "no";

	}

	/**
	 * 提交注册
	 * 
	 * @param date
	 */
	@ResponseBody
	@RequestMapping("/register")
	public Integer register(User user, String code) {

		Integer row = us.register(user, code);

		return row;
		

	}

	/**
	 * 登录验证
	 * 
	 * @param date
	 */
	@ResponseBody
	@RequestMapping("/login")
	public User login(@RequestBody User user) {

		String uname = user.getUname();
		String pwd = user.getPwd();

		// 逻辑层
		User loginUser = us.login(uname, pwd);
		return loginUser;

	}

	/**
	 * 注销
	 * 
	 * @param date
	 */
	@ResponseBody
	@RequestMapping("/logout")
	public String logout(HttpServletRequest req) {
		HttpSession session = req.getSession();
		session.removeAttribute("loginUname");
		session.removeAttribute("loginUid");
		return "ok";

	}

	/**
	 * 查询个人资料
	 * 
	 * @param date
	 */
	@ResponseBody
	@RequestMapping("/searchPersonalData")
	public Object searchPersonalData(HttpServletRequest req) {
		HttpSession session = req.getSession();
		// 从session域中获取用户id
		Integer uid = Integer.parseInt(session.getAttribute("loginUid").toString());
		User user = us.findPersonalDataById(uid);
		return user;

	}

	/**
	 * 个人资料界面,上传图片
	 * 
	 * @param date
	 */
	@ResponseBody
	@RequestMapping("/uploadHead")
	public String uploadHead(MultipartFile file, HttpServletRequest req) {// @RequestParam("headfile")
		// 获取文件名
		String fileName = file.getOriginalFilename();
		// 获取最后一个点号出现的索引
		int lastIndexOf = fileName.lastIndexOf(".");
		// 通过该索引截取文件名的后缀名
		String suffix = fileName.substring(lastIndexOf);
		// 通过UUid算出随机名称
		String newFileName = UUID.randomUUID().toString().replace("-", "");
		// 确定路径加文件名
		String path = "D:/paipaiimg/user_head/" + newFileName + suffix;
		try {
			// 保存文件到本地
			file.transferTo(new File(path));
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 从session中获取用户id
		HttpSession session = req.getSession();
		int uid = Integer.parseInt(session.getAttribute("loginUid").toString());
		// 更新数据库
		Integer row = us.updateUserHeadImg(uid, newFileName + suffix);

		// 返回
		return row > 0 ? "ok" : "no";

	}

	@Autowired
	private AddressService addressService;

	/**
	 * 定时任务 查询默认用户地址
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping("/findDefaultAddressByUserId")
	@ResponseBody
	public Address findDefaultAddressByUserId(@RequestParam("userId") Integer userId) {
		Address address = addressService.findDefaultAddressByUserId(userId);
		return address;

	};

}